package com.wangqinlei.cowims126.controller;

import com.wangqinlei.cowims126.pojo.Breeder;
import com.wangqinlei.cowims126.pojo.Cow;
import com.wangqinlei.cowims126.pojo.Feed;
import com.wangqinlei.cowims126.service.BreederService;
import com.wangqinlei.cowims126.service.CowService;
import com.wangqinlei.cowims126.service.FeedService;
import com.wangqinlei.cowims126.service.FoodService;
import com.wangqinlei.cowims126.util.AjaxResult;
import com.wangqinlei.cowims126.util.Const;
import com.wangqinlei.cowims126.util.PageBean;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 王勤磊
 * 饲养控制器
 */
@Controller
@RequestMapping("/feed")
public class FeedController {

    @Autowired
    private FeedService feedService;
    @Autowired
    private CowService cowService;
    @Autowired
    private FoodService foodService;
    @Autowired
    private BreederService breederService;

    @GetMapping("/feed_list")
    public String feedList(){
        return "/feed/feedList";
    }


    /**
     * 异步加载饲喂列表
     * @param page
     * @param rows
     * @param cowid
     * @param foodid
     * @param from
     * @param session
     * @return
     */
    @RequestMapping("/getFeedList")
    @ResponseBody
    public Object getFeedList(@RequestParam(value = "page", defaultValue = "1")Integer page,
                                    @RequestParam(value = "rows", defaultValue = "100")Integer rows,
                                    @RequestParam(value = "cowid", defaultValue = "0")String cowid,
                                    @RequestParam(value = "foodid", defaultValue = "0")String foodid,
                                    @RequestParam(value = "breederid", defaultValue = "0")String breederid,
                                    String from, HttpSession session){
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",page);
        paramMap.put("pagesize",rows);
        if(!cowid.equals("0"))  paramMap.put("cowid",cowid);
        if(!foodid.equals("0"))  paramMap.put("foodid",foodid);
        if(!breederid.equals("0"))  paramMap.put("breederid",breederid);

        Breeder breeder = (Breeder) session.getAttribute(Const.BREEDER);
        if(!StringUtils.isEmpty(breeder)){
            //是饲养员权限，只能查询自己的信息
            paramMap.put("breederid",breeder.getId());
        }
        PageBean<Feed> pageBean = feedService.queryPage(paramMap);
        if(!StringUtils.isEmpty(from) && from.equals("combox")){
            return pageBean.getDatas();
        }else{
            Map<String,Object> result = new HashMap();
            result.put("total",pageBean.getTotalsize());
            result.put("rows",pageBean.getDatas());
            return result;
        }
    }


    /**
     * 添加饲喂记录
     * @param feed
     * @return
     */
    @PostMapping("/addFeed")
    @ResponseBody
    public AjaxResult addFeed(Feed feed){
        AjaxResult ajaxResult = new AjaxResult();
        //判断是否已录入成绩
        if(feedService.isFeed(feed)){
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("已录入，请勿重复录入！");
        }else{
            int count = feedService.addFeed(feed);
            if(count > 0){
                ajaxResult.setSuccess(true);
                ajaxResult.setMessage("录入成功");
            }else{
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("系统错误，请重新录入");
            }
        }
        return ajaxResult;
    }


    /**
     * 修改饲喂记录
     * @param feed
     * @return
     */
    @PostMapping("/editFeed")
    @ResponseBody
    public AjaxResult editFeed(Feed feed){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            //判断是否已录入成绩
            if(feedService.isFeed(feed)){
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("已录入，请勿重复录入！");
            }else{
            int count = feedService.editFeed(feed);
            if(count > 0){
                ajaxResult.setSuccess(true);
                ajaxResult.setMessage("修改成功");
            }else{
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("系统错误，请重新修改");
            }}
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("系统错误，请重新修改");
        }
        return ajaxResult;
    }

    /**
     * 删除饲喂记录
     * @param id
     * @return
     */
    @PostMapping("/deleteFeed")
    @ResponseBody
    public AjaxResult deleteFeed(Integer id){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            int count = feedService.deleteFeed(id);
            if(count > 0){
                ajaxResult.setSuccess(true);
                ajaxResult.setMessage("删除成功");
            }else{
                ajaxResult.setSuccess(false);
                ajaxResult.setMessage("系统错误，请重新删除");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("系统错误，请重新删除");
        }
        return ajaxResult;
    }

    /**
     * 导入xlsx表 并存入数据库
     * @param importFeed
     * @param response
     */
    @PostMapping("/importFeed")
    @ResponseBody
    public void importFeed(@RequestParam("importFeed") MultipartFile importFeed, HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        try {
            InputStream inputStream = importFeed.getInputStream();
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
            int count = 0;
            String errorMsg = "";
            for(int rowNum = 1; rowNum <= sheetAt.getLastRowNum(); rowNum++){
                XSSFRow row = sheetAt.getRow(rowNum); // 获取第rowNum行
                //第0列
                XSSFCell cell = row.getCell(0); // 获取第rowNum行的第0列 即坐标（rowNum，0）
                if(cell == null){
                    errorMsg += "第" + rowNum + "行牛编号缺失！\n";
                    continue;
                }
                //第1列
                cell = row.getCell(1);
                if(cell == null){
                    errorMsg += "第" + rowNum + "行食物缺失！\n";
                    continue;
                }
                //第2列
                cell = row.getCell(2);
                if(cell == null){
                    errorMsg += "第" + rowNum + "行饲喂量缺失！\n";
                    continue;
                }
                double feedValue = cell.getNumericCellValue();
                //第3列
                cell = row.getCell(3);
                if(cell == null){
                    errorMsg += "第" + rowNum + "行饲养员缺失！\n";
                    continue;
                }
                //第4列
                cell = row.getCell(4);
                String remark = null;
                if(cell != null){
                    remark = cell.getStringCellValue();
                }

                //转换为id,存入数据库
                // 1)首先获取对应的id
                int cowId = cowService.findBySn(row.getCell(0).getStringCellValue());
                int foodId = foodService.findByName(row.getCell(1).getStringCellValue());
                int breederId = breederService.findByName(row.getCell(3).getStringCellValue());
                // 2)判断是否已存在数据库中
                Feed feed = new Feed();
                feed.setCowId(cowId);
                feed.setFoodId(foodId);
                feed.setFeedWeight(feedValue);
                feed.setBreederId(breederId);
                feed.setRemark(remark);
                if(!feedService.isFeed(feed)){
                    // 3)存入数据库
                    int i = feedService.addFeed(feed);
                    if(i > 0){
                        count ++ ;
                    }
                }else{
                    errorMsg += "第" + rowNum + "行已录入，不重复录入！\n";
                }
            }
            errorMsg += "成功录入" + count + "条成绩信息！";
            response.getWriter().write("<div id='message'>"+errorMsg+"</div>");

        } catch (IOException e) {
            e.printStackTrace();
            try {
                response.getWriter().write("<div id='message'>上传错误</div>");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }


    /**
     * 导出xlsx表
     * @param response
     * @param feed
     * @param session
     */
    @RequestMapping("/exportFeed")
    @ResponseBody
    private void exportFeed(HttpServletResponse response, Feed feed, HttpSession session) {
        //获取当前登录用户类型
        Breeder breeder = (Breeder) session.getAttribute(Const.BREEDER);
        if(!StringUtils.isEmpty(breeder)){
            feed.setBreederId(breeder.getId());
        }
        if(feed.getBreederId()==0) feed.setBreederId(null);
        if(feed.getCowId()==0) feed.setCowId(null);
        if(feed.getFoodId()==0) feed.setFoodId(null);
        try {
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("feed_list.xls", "UTF-8"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/octet-stream");
            ServletOutputStream outputStream = response.getOutputStream();
            List<Feed> feedList = feedService.getAll(feed);
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
            XSSFSheet createSheet = xssfWorkbook.createSheet("饲养列表");
            XSSFRow createRow = createSheet.createRow(0);
            createRow.createCell(0).setCellValue("牛编号");
            createRow.createCell(1).setCellValue("食物名称");
            createRow.createCell(2).setCellValue("饲喂量");
            createRow.createCell(3).setCellValue("饲养员");
            createRow.createCell(4).setCellValue("备注");
            //实现将数据装入到excel文件中
            int row = 1;
            for( Feed s:feedList){
                createRow = createSheet.createRow(row++);
                createRow.createCell(0).setCellValue(s.getCowSn());
                createRow.createCell(1).setCellValue(s.getFoodName());
                createRow.createCell(2).setCellValue(s.getFeedWeight());
                createRow.createCell(3).setCellValue(s.getBreederName());
                createRow.createCell(4).setCellValue(s.getRemark());
            }
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
